package mail.fetch.qq;

import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import mail.util.CookieParser;
import mail.util.JsInvoker;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-1-14 15:44:24
 * @Desc: 登录, 获取登陆凭据
 */
@Deprecated
public class Login {

    private Map<String, String> cookieRepository;
    private String account;
    private String pwd;
    private String filePath = "F:\\workspace\\java\\MailCrawler\\src\\main\\resources\\EncryptQq.js";
    private Fetcher fetcher;

    Login(String account, String pwd) {
        this.pwd = pwd;
        this.account = account;
        fetcher = new Fetcher();
        cookieRepository = new HashMap<>();
        String pgvPvi = getPgv(0);
        String pgvSi = getPgv(1);
        cookieRepository.put("pgv_pvi", pgvPvi);
        cookieRepository.put("pgv_si", pgvSi);
        cookieRepository.put("ptui_loginuin", account);
    }

    public Map<String, String> getCookieRepository() throws Exception {
        xLogin();
        checkRegMaster();
        String checkSigUrl = loginU();
        checkSig(checkSigUrl);
        loginVt();

        return cookieRepository;
    }

    private void xLogin() throws Exception {
        String url = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.fetch.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.fetch.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.fetch.qq.com/zh_CN/htmledition/style/ptlogin_input24e6b9.css";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "xui.ptlogin2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Referer", "https://mail.fetch.qq.com/"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
        };

        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
    }

    /**
     * 获取cookie和返回值
     *
     * @throws Exception 异常
     */
    private void checkRegMaster() throws Exception {
        String url = "https://ssl.ptlogin2.qq.com/check?" + "regmaster=" +
                "&pt_tea=2" +
                "&pt_vcode=1" +
                "&uin=" + account +
                "&appid=522005705" +
                "&js_ver=10291" +
                "&js_type=1" +
                "&login_sig=" + cookieRepository.get("pt_login_sig") +
                "&u1=https%3A%2F%2Fmail.qq.com%2Fcgi-bin%2Freadtemplate%3Fcheck%3Dfalse%26t%3Dloginpage_new_jump%26vt%3Dpassport%26vm%3Dwpt%26ft%3Dloginpage%26target%3D" +
                "&r=0.8591487157144195" +
                "&pt_uistyle=25";
        String cookie = "pt_login_sig=" + cookieRepository.get("pt_login_sig") +
                ";pt_clientip=" + cookieRepository.get("pt_clientip") +
                ";pt_serverip=" + cookieRepository.get("pt_serverip") +
                ";pt_local_token=" + cookieRepository.get("pt_local_token") +
                ";uikey=" + cookieRepository.get("uikey") +
                ";pt_guid_sig=" + cookieRepository.get("pt_guid_sig") +
                ";pgv_pvi=" + cookieRepository.get("pgv_pvi") +
                ";pgv_si=" + cookieRepository.get("pgv_si");
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "ssl.ptlogin2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.fetch.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.fetch.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.fetch.qq.com/zh_CN/htmledition/style/ptlogin_input24e6b9.css"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
        String pageContent = map.get("page-content").get(0);
        String verifyCode = pageContent.substring(pageContent.indexOf(",'") + 2, pageContent.indexOf("','\\x"));
        cookieRepository.put("verifycode", verifyCode);
        String encryptCode = pageContent.substring(pageContent.indexOf("\\x"));
        encryptCode = encryptCode.substring(0, encryptCode.indexOf("','"));
        encryptCode = encryptCode.replace("\\x", "");
        cookieRepository.put("encryptCode", encryptCode);
        String randSalt = pageContent.substring(pageContent.lastIndexOf("','") + 3);
        randSalt = randSalt.substring(0, randSalt.indexOf(")"));
        cookieRepository.put("pt_randsalt", randSalt);
    }

    /**
     * 登录最后一步
     *
     * @throws Exception 抛出异常
     */
    private String loginU() throws Exception {

        long ac = System.currentTimeMillis();
        String verifyCode = cookieRepository.get("verifycode");
        String encryptCode = cookieRepository.get("encryptCode");
        String encryptPwd = encrypt(encryptCode, verifyCode);
        String url = "https://ssl.ptlogin2.qq.com";
        String param = "/login?" + "u=" + account +
                "&verifycode=" + verifyCode +
                "&pt_vcode_v1=0" +
                "&pt_verifysession_v1=" + cookieRepository.get("ptvfsession") +
                "&p=" + encryptPwd +
                "&pt_randsalt=" + cookieRepository.get("pt_randsalt") +
                "&u1=https%3A%2F%2Fmail.qq.com%2Fcgi-bin%2Freadtemplate%3Fcheck%3Dfalse%26t%3Dloginpage_new_jump%26vt%3Dpassport%26vm%3Dwpt%26ft%3Dloginpage%26target%3D%26account%3D" + account +
                "&ptredirect=" + "0" +
                "&h=" + "1" +
                "&t=" + "1" +
                "&g=" + "1" +
                "&from_ui=" + "1" +
                "&ptlang=" + "2052" +
                "&action=" + "1-22-" + ac +
                "&js_ver=10291" +
                "&js_type=1" +
                "&login_sig=" + cookieRepository.get("pt_login_sig") +
                "&pt_uistyle=25" +
                "&aid=522005705" +
                "&daid=" + "4" +
                "&";
        url += param;
        String cookie = "ptui_loginuin=" + account +
                ";confirmuin=0" +
                ";ptisp=ctc" +
                ";ptdrvs=" + cookieRepository.get("ptdrvs") +
                ";ptvfsession=" + cookieRepository.get("ptvfsession");
        RequestHeader[] requestHeaders = {
                new RequestHeader("%3aauthority", "ssl.ptlogin2.qq.com"),
                new RequestHeader("%3amethod", "GET"),
                new RequestHeader("%3apath", param),
                new RequestHeader("%3ascheme", "https"),
                new RequestHeader("accept", "*/*"),
                new RequestHeader("accept-encoding", "gzip, deflate, br"),
                new RequestHeader("accept-language", "zh-CN,zh;q=0.9"),
                new RequestHeader("cookie", cookie),
                new RequestHeader("referer", "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.fetch.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.fetch.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.fetch.qq.com/zh_CN/htmledition/style/ptlogin_input24e6b9.css"),
                new RequestHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")
        };

        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
        String pageContent = map.get("page-content").get(0);
        String checkSigUrl = pageContent.substring(pageContent.indexOf("https"));
        checkSigUrl = checkSigUrl.substring(0, checkSigUrl.indexOf("','0','登录成功"));
        return checkSigUrl;
    }

    /**
     * 从loginU()取得的跳转url
     *
     * @param checkSigUrl 获取cookie
     * @throws Exception 抛出异常
     */
    private void checkSig(String checkSigUrl) throws Exception {
        StringBuilder cookie = new StringBuilder();
        cookie.append("pgv_pvi=").append(cookieRepository.get("pgv_pvi"))
                .append(";pgv_si=").append(cookieRepository.get("pgv_si"))
                .append(";ptisp=").append(cookieRepository.get("ptisp"))
                .append(";ptui_loginuin=").append(cookieRepository.get("ptui_loginuin"))
                .append(";uin=").append(cookieRepository.get("uin"))
                .append(";skey=").append(cookieRepository.get("skey"))
                .append(";RK=").append(cookieRepository.get("RK"))
                .append(";ptcz=").append(cookieRepository.get("ptcz"));
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "ssl.ptlogin2.mail.fetch.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Referer", "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.fetch.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.fetch.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.fetch.qq.com/zh_CN/htmledition/style/ptlogin_input24e6b9.css"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie.toString())
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(checkSigUrl, requestHeaders, 1000 * 3, 1000 * 3, false, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
    }

    private void loginVt() throws Exception {
        String url = "https://mail.fetch.qq.com/cgi-bin/login?vt=passport&vm=wpt&ft=loginpage&target=";
        StringBuilder cookie = new StringBuilder();
        cookie.append("pgv_pvi=").append(cookieRepository.get("pgv_pvi"))
                .append(";pgv_si=").append(cookieRepository.get("pgv_si"))
                .append(";ptisp=").append(cookieRepository.get("ptisp"))
                .append(";ptui_loginuin=").append(cookieRepository.get("ptui_loginuin"))
                .append(";uin=").append(cookieRepository.get("uin"))
                .append(";skey=").append(cookieRepository.get("skey"))
                .append(";RK=").append(cookieRepository.get("RK"))
                .append(";ptcz=").append(cookieRepository.get("ptcz"))
                .append(";p_uin=").append(cookieRepository.get("p_uin"))
                .append(";pt4_token=").append(cookieRepository.get("pt4_token"))
                .append(";p_skey=").append(cookieRepository.get("p_skey"));
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "mail.fetch.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Referer", "https://mail.fetch.qq.com/"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie.toString())
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, false, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
        String location = map.get("Location").get(0);
        String sidu = location.substring(location.indexOf("sid=") + 4);
        sidu = sidu.substring(0, sidu.indexOf("&r="));
        cookieRepository.put("sidu", sidu);
    }//UrZvHGtVwKabgyJ_

    /**
     * 使用js引擎加密密码
     *
     * @param encryptCode 加密代码
     * @param verifyCode  验证码
     * @return 加密后的密码
     */
    private String encrypt(String encryptCode, String verifyCode) {
        String method = "encode('" + pwd + "','" + encryptCode + "','" + verifyCode + "')";

        return JsInvoker.invokeJs(method, filePath);
    }

    /**
     * 获取pgv的两个参数(这两个参数好像没什么作用)
     *
     * @param i 参数类型
     * @return 参数
     */
    private String getPgv(int i) {
        String method;
        if (i == 0) {
            method = "pgv_pvi()";
        } else {
            method = "pgv_si()";
        }
        return JsInvoker.invokeJs(method, filePath);
    }
}